import {
  getQrcodeByWxAndQQ,
  pollingScanApi
} from '@/api/business/staylnventory'

export const qrcodeMixin = {
  data() {
    return {
      qrcodeForm: { //二维码轮询
        authType: '',
        uuid: '',
        dictCodeId: '',
        id: ''
      },
      timer: null, //轮询
      QQLoading: false,
      WxLoading: false
    }
  },
  methods: {
    // 获取二维码
    onAuth(type) {
      this.qrcodeForm.authType = type;
      this.qrcodeForm.dictCodeId = this.form.dictCodeId;
      this.qrcodeForm.id = this.form.id;
      this.qrcodeUrl = '';

      if (type == 1) this.QQLoading = true;
      if (type == 2) this.WxLoading = true;

      console.log(this.QQLoading)

      getQrcodeByWxAndQQ({
        authType: type,
        dictCodeId: this.form.dictCodeId
      }).then(res => {
        this.dialogVisible = true;
        this.QQLoading = false;
        this.WxLoading = false;

        if (res.data.url && res.data.url.indexOf('http') > -1) {
          this.qrcodeUrl = res.data.url;
        } else {
          this.qrcodeUrl = 'data:image/png;base64,' + res.data.url;
        }

        if (res.data.hasOwnProperty('uuid')) {
          this.qrcodeForm.uuid = res.data.uuid;
        }
      }).catch(() => {
        this.QQLoading = false;
        this.WxLoading = false;
      })
    },

    // 扫码轮询 200关 500不关
    handleScanDone() {
      this.QQLoading = true;
      pollingScanApi(this.qrcodeForm).then(resp => {
        this.QQLoading = false;
        if (this.timer != null) {
          clearInterval(this.timer);
          this.timer = null;
        }

        let res = resp.data;
        if (res.code == 400 || res.code == 401 || res.code == 403 || res.code == 500) {
          this.$message.error(res.msg);
          this.dialogVisible = false;
        } else if (res.code == 202 || res.code == 302) {
          this.$message.info(res.msg);
          // 轮询是否扫码成功
          this.timer = setInterval(() => {
            this.handleScanDone();
          }, 3000)
        } else if (res.code == 200) {
          this.$message.success(res.msg);
          this.dialogVisible = false;
          this.form.description = res.description
        }
      }).then(res => {
        this.QQLoading = false;
      })
    },
  }
}
